import axios from 'axios' // 引入axios
// axios 默认配置  更多配置查看Axios中文文档
axios.defaults.timeout = 50000 // 超时默认值
axios.defaults.baseURL = '/api' // 默认baseURL
axios.defaults.responseType = 'text' // 默认数据响应类型
axios.defaults.headers.common['Content-Type'] = 'application/json;charset=UTF-8'
axios.defaults.headers.common['Accept'] = 'application/json'
// axios.defaults.withCredentials = true;           // 表示跨域请求时是否需要使用凭证
// http request 拦截器
axios.interceptors.request.use(
  (config) => {
    // 设置token
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)
// http response 拦截器
// ajax请求回调之前拦截 对请求返回的信息做统一处理 比如error为401无权限则跳转到登陆界面
axios.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    return error.response
  }
  //
)
export default axios // 这句千万不能漏下！！！
/**
 * post 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post(url: string, data = {}) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url: url,
      /* headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},*/
      headers: { 'Content-Type': 'application/json;charset=UTF-8' },
      data: JSON.stringify(data)
    }).then(
      (response) => {
        resolve(response.data)
      },
      (err) => {
        reject(err)
      }
    )
  })
}

/**
 * get 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
export function get(url: string, data = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, { params: data }).then(
      (response) => {
        resolve(response.data)
      },
      (err) => {
        reject(err)
      }
    )
  })
}

/**
 *  删除
 * @param url
 * @param data
 */
export function del(url: string, data = {}) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'delete',
      url: url,
      /* headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},*/
      headers: { 'Content-Type': 'application/json;charset=UTF-8' },
      data: JSON.stringify(data)
    }).then(
      (response) => {
        resolve(response.data)
      },
      (err) => {
        reject(err)
      }
    )
  })
}

/**
 * 可以查看中文文档 自行封装
 */
export function requestAssign(url: string, data = {}, method: any) {
  return new Promise((resolve, reject) => {
    if (method.toLowerCase() === 'get'.toLowerCase()) {
      resolve(get(url, data))
    } else if (method.toLowerCase() === 'post'.toLowerCase()) {
      resolve(post(url, data))
    } else if (method.toLowerCase() === 'delete'.toLowerCase()) {
      resolve(del(url, data))
    }
  })
}
